package com.wjk.kylin.id.core.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.wjk.kylin.id.core.spring.boot.autoconfigure.kid.KylinIdInfoConfig;
import com.wjk.kylin.id.core.entity.SegmentId;
import com.wjk.kylin.id.core.service.SegmentIdService;
import com.wjk.kylin.id.core.util.HttpUtil;
import com.wjk.kylin.id.core.dto.BaseOutDTO;
import com.wjk.kylin.id.core.dto.IdInfoDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

/**
 *
 */
public class HttpSegmentIdServiceImpl implements SegmentIdService {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpSegmentIdServiceImpl.class);
    //http请求参数
    private final String params;

    public HttpSegmentIdServiceImpl(String bizType) {
        this.params = "{\"token\":\"" + KylinIdInfoConfig.getInstance().getToken() + "\",\"bizType\":\"" + bizType + "\"}";
    }

    /**
     * http请求 查询id
     *
     * @return
     */
    @Override
    public SegmentId getNextSegmentId() {
        String url = this.chooseService();
        long startTime = System.currentTimeMillis();
        String response = HttpUtil.doPost(url, this.params);
        LOGGER.info("kylin-id client getNextSegmentId end,url:{}, request:{},response:{},耗时{}ms", url, this.params, response, System.currentTimeMillis() - startTime);
        if (StringUtils.isBlank(response)) {
            return null;
        }
        BaseOutDTO<IdInfoDTO> outDTO = JSON.parseObject(response, new TypeReference<BaseOutDTO<IdInfoDTO>>() {
        });
        if (outDTO == null) {
            return null;
        }
        if (outDTO.getCode() != 200) {
            LOGGER.error("kylin-id client getNextSegmentId end,url:{}, request:{},response:{}", url, this.params, response);
            return null;
        }
        IdInfoDTO data = outDTO.getData();
        if (data == null) {
            LOGGER.error("kylin-id client getNextSegmentId end,url:{}, request:{},response:{}", url, this.params, response);
            return null;
        }

        SegmentId segmentId = new SegmentId();
        segmentId.setCurrentId(new AtomicLong(data.getBeginId()));
        //如果最大值是100，则到95就要请求获取下一次的起始id
        long loadingId = (long) ((data.getMaxId() - data.getBeginId()) * KylinIdInfoConfig.getInstance().getLoadIdThreshold());
        segmentId.setLoadingId(data.getBeginId() + loadingId);
        segmentId.setMaxId(data.getMaxId());
        segmentId.setDelta(data.getDelta());
        return segmentId;
    }

    /**
     * 随机获取mes服务地址
     *
     * @return
     */
    private String chooseService() {
        List<String> serverList = KylinIdInfoConfig.getInstance().getServerList();
        if (CollectionUtils.isEmpty(serverList)) {
            throw new NullPointerException("server is null");
        }
        String url = "";
        if (serverList.size() == 1) {
            url = serverList.get(0);
        } else if (serverList.size() > 1) {
            url = serverList.get(new Random().nextInt(serverList.size()));
        }
        return url;
    }

}
